package com.geline.easytrans.serializer;

import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.geline.easytrans.annotation.DictText;
import com.geline.easytrans.handler.TransDictHandler;
import com.geline.easytrans.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Objects;

/**
 * @author mx
 * @date 2025/11/8
 */
@Slf4j
public class DictTextSerializer extends StdSerializer<Object> implements ContextualSerializer {
    private String dictType;
    private String newFieldName;

    public DictTextSerializer(){
        super(Object.class);
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if(value==null){
            gen.writeNull();
            return;
        }
        gen.writeObject(value);
        TransDictHandler transDictHandler = SpringUtil.getBean(TransDictHandler.class);
        String dictLabel = transDictHandler.getDictLabel(dictType, value);
        //在新字段中写入翻译label
        if(StringUtils.isBlank(this.newFieldName)){
            this.newFieldName = gen.getOutputContext().getCurrentName() + "Desc";
        }
        gen.writeStringField(this.newFieldName, dictLabel);
    }

    /**
     * 获取属性上的注解属性
     */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        if(property==null){
            return prov.findNullValueSerializer(null);
        }
        DictText annotation = property.getAnnotation(DictText.class);
        if (annotation!=null && Objects.equals(String.class, property.getType().getRawClass())) {
            this.dictType = annotation.value();
            this.newFieldName = annotation.target();
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
